﻿using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace FastAccess
{
	static class Utils
	{
		public const int SW_RESTORE = 9;
		
		public static Config AppConfig { get; set; }


		public static string GetVersion()
		{
			Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
			return string.Format("FastAccess {0}.{1} (Beta)", ver.Major, ver.Minor);
		}

		public static void LoadConfig()
		{
			AppConfig = Config.Deserialize("FastAccess.Config.XML");
			if (AppConfig == null)
				AppConfig = new Config();
		}

		public static void SaveConfig()
		{
			AppConfig.Serialize("FastAccess.Config.XML");
		}

		/// <summary>
		/// Runs the Program on Startup.
		/// </summary>
		/// <param name="startup">True to Run on Startup, False to NOT Run on Startup.</param>
		public static void RunOnStartUp(bool startup)
		{
			RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
			if (startup == true)
				key.SetValue(Application.ProductName, Application.ExecutablePath.ToString());
			else
				key.DeleteValue(Application.ProductName, false);
		}

		public static bool IsOnStartup()
		{
			RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
			if (key.GetValue(Application.ProductName) != null)
				return true;
			else
				return false;
		}
		
		[DllImport("user32.dll")]
		private static extern bool SetForegroundWindow(IntPtr hWnd);

		[DllImport("user32.dll")]
		private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
		
		[DllImport("user32.dll")]
		private static extern bool FlashWindow(IntPtr hwnd, bool bInvert);
		
		public static bool ShowFastAccess(Process p)
		{
			ShowWindow(p.MainWindowHandle, SW_RESTORE);
			return SetForegroundWindow(p.MainWindowHandle);
		}
		
		public static Process FastAccessProcess()
		{
			Process AuxProccess = null;
			System.Diagnostics.Process AccessProcess = System.Diagnostics.Process.GetCurrentProcess();
			string ProcName = AccessProcess.ProcessName;
			if (System.Diagnostics.Process.GetProcessesByName(ProcName).Length > 1)
			{
				foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName(ProcName))
				{
					if (p.Id!=AccessProcess.Id)
					{
						AuxProccess = p;
						break;
					}
				}
			}
			return AuxProccess;
		}
		
		public static bool ExistsFastAccess()
		{
			Process FastProcess = FastAccessProcess();
			if (FastProcess != null)
			{
				FlashWindow(FastProcess.MainWindowHandle,true);
				return Utils.ShowFastAccess(FastProcess);
			}
			else
				return false;
		}
	}
}
